# -*- coding: utf-8 -*-
from config import DEFAULT_ACTIVITY_COVER_PATH, DEFAULT_USER_PORTRAIT_PATH
from database import Base, db_session
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, Enum, ForeignKey
from sqlalchemy.orm import relationship, backref
from datetime import datetime

class BaseModel():
    @classmethod
    def get(cls, id):
        return cls.query.get(id)
    def save(self):
        if self.id is None:
            db_session.add(self)
        db_session.commit()

class User(Base, BaseModel):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    portrait = Column(String(100), default=DEFAULT_USER_PORTRAIT_PATH)
    discriminator = Column('type', String(50))
    __mapper_args__ = {'polymorphic_on': discriminator}
    def __init__(self, name, portrait):
        self.name = name
        self.portrait = portrait
    def __repr__(self):
        return self.name
    
class RenrenUser(User):
    __tablename__ = 'renren_user'
    __mapper_args__ = {'polymorphic_identity': 'renren'}
    id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    renren_id = Column(Integer)
    def __init__(self, name, portrait, id):
        self.renren_id = id
        super(RenrenUser, self ).__init__(name, portrait)
    
    
class ActivityInvite(Base, BaseModel):
    __tablename__ = 'activity_invite'
    response = Column(Enum(u'参加', u'可能参加', u'不参加', u'未处理', u'待审核'))
    user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    participant = relationship('User', backref='activity_invites') 
    activity_id = Column(Integer, ForeignKey('activity.id'), primary_key=True)
#    def __unicode__(self):
#        return self.response
#    def join(self):
#        self.response = 'Y'
#        self.save()
#        if not UserActivityPreference.objects.filter(user=self.user, activity_type=self.activity.activity_type).exists():
#            try:
#                preference = UserActivityPreference.objects.get(user=self.activity.invitor, activity_type=self.activity.activity_type)
#                preference.id = None
#                preference.user = self.user
#                preference.save()
#            except:
#                pass
    
class ActivityType(Base, BaseModel):
    __tablename__ = 'activity_type'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    def __repr__(self):
        return self.name
    
class Activity(Base, BaseModel):
    __tablename__ = 'activity'
    id = Column(Integer, primary_key=True)
    creator_id = Column(Integer, ForeignKey('user.id'))
    creator = relationship('User', backref='activities_created')
    title = Column(String(50))
    image = Column(String(50), default=DEFAULT_ACTIVITY_COVER_PATH)
    activity_type_id = Column(Integer, ForeignKey('activity_type.id'))
    activity_type = relationship('ActivityType', backref='activities')
    description = Column(Text)
    start_time = Column(DateTime, nullable=True)
    create_time = Column(DateTime, default=datetime.now)
    end_time = Column(DateTime, nullable=True)
    activity_place = Column(String(100))
    invites = relationship('ActivityInvite', backref='activity', lazy='dynamic')
    #公开�
    is_public = Column(Boolean, default=True)
    #申请是否需要审�
    need_approve = Column(Boolean, default=False)
    #是否允许活动成员邀请ta的朋�
    allow_invitee_invite = Column(Boolean, default=True)
    state = Column(Enum(u'征人', u'进行', u'结束', u'取消', name='activity_state'), default=u'征人', nullable=False)
    @property
    def start_time_display(self):
        return self.start_time.strftime('%Y.%m.%d %H:%M')
    @property
    def end_time_display(self):
        return self.end_time.strftime('%Y.%m.%d %H:%M')
    def add_invitee(self, user, response):
        invite = ActivityInvite()
        invite.participant = user
        invite.response = response
        self.invites.append(invite)
    def add_invitees(self, users, response):
        for user in users:
            self.add_invitee(user, response)
    def is_public_display(self):
        if self.is_public == True:
            return u'公开活动'
        else:
            return u'私有活动'
    @property
    def attended_invites(self):
        return self.invites.filter(ActivityInvite.response == u'参加')
    @property
    def maybe_attend_invites(self):
        return self.invites.filter(ActivityInvite.response == u'可能参加')
    @property
    def unhandled_invites(self):
        return self.invites.filter(ActivityInvite.response == u'未处理')
    @property
    def declined_invites(self):
        return self.invites.filter(ActivityInvite.response == u'不参加')